package org.zhengquan.service;

import com.google.common.base.Preconditions;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zhengquan.common.RequestHolder;
import org.zhengquan.dao.SysAclMapper;
import org.zhengquan.dao.SysAclModuleMapper;
import org.zhengquan.exception.ParamException;
import org.zhengquan.pojo.SysAclModule;
import org.zhengquan.util.BeanValidator;
import org.zhengquan.util.IpUtil;
import org.zhengquan.util.LevelUtil;
import org.zhengquan.vo.AclModuleVO;

import java.util.Date;
import java.util.List;

/**
 * @author zhengquan
 * @date 2017/11/2
 */
@Service
public class SysAclModuleService {

    @Autowired
    private SysAclModuleMapper sysAclModuleMapper;

    @Autowired
    private SysAclMapper sysAclMapper;

    @Autowired
    private SysLogService sysLogService;

    public void save(AclModuleVO aclModuleVO) {
        BeanValidator.check(aclModuleVO);
        if (checkExit(aclModuleVO.getParentId(), aclModuleVO.getId(), aclModuleVO.getName())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule sysAclModule = SysAclModule.builder().name(aclModuleVO.getName()).parentId(aclModuleVO.getParentId())
                .state(aclModuleVO.getState()).remark(aclModuleVO.getRemark()).build();
        sysAclModule.setLevel(LevelUtil.calculateLevel(getLevel(sysAclModule.getParentId()), sysAclModule.getParentId()));
        sysAclModule.setOperator(RequestHolder.getCurrentUser().getUsername());
        sysAclModule.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysAclModule.setOperateTime(new Date());
        sysAclModuleMapper.insertSelective(sysAclModule);
        sysLogService.saveAclModuleLog(null,sysAclModule);
    }

    public void update(AclModuleVO aclModuleVO) {
        BeanValidator.check(aclModuleVO);
        if (checkExit(aclModuleVO.getParentId(), aclModuleVO.getId(), aclModuleVO.getName())) {
            throw new ParamException("同一层级下存在相同名称的权限模块");
        }
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(aclModuleVO.getId());
        Preconditions.checkNotNull(before,"待更新的权限模块不存在");
        SysAclModule after = SysAclModule.builder().id(aclModuleVO.getId()).name(aclModuleVO.getName()).parentId(aclModuleVO.getParentId())
                .state(aclModuleVO.getState()).seq(aclModuleVO.getSeq()).remark(aclModuleVO.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(after.getParentId()), after.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        updateWithChild(before,after);
        sysLogService.saveAclModuleLog(before,after);
    }

    public void delete(Integer aclModuleId) {
        SysAclModule sysAclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        Preconditions.checkNotNull(sysAclModule, "待删除的权限模块不存在,无法删除");
        if (sysAclModuleMapper.countByParentId(aclModuleId) > 0) {
            throw new ParamException("当前权限模块下有子模块,无法删除");
        }
        if (sysAclMapper.countByAclModuleId(aclModuleId) > 0) {
            throw new ParamException("当前权限模块下有权限点,无法删除");
        }
        sysAclModuleMapper.deleteByPrimaryKey(aclModuleId);
    }

    @Transactional(rollbackFor = Exception.class)
    private void updateWithChild(SysAclModule before, SysAclModule after) {
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        if (!newLevelPrefix.equals(oldLevelPrefix)) {
            List<SysAclModule> aclModuleList = sysAclModuleMapper.selectChildAclModuleListByLevel(new StringBuilder(oldLevelPrefix).append(".").append(before.getId()).toString());
            if (CollectionUtils.isNotEmpty(aclModuleList)) {
                for (SysAclModule sysAclModule : aclModuleList) {
                    String level = sysAclModule.getLevel();
                    if (level.indexOf(oldLevelPrefix) == 0) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        sysAclModule.setLevel(level);
                    }
                }
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKeySelective(after);
    }

    private boolean checkExit(Integer parentId, Integer aclModuleId, String aclModuleName) {
        return sysAclModuleMapper.countByNameAndParentId(parentId, aclModuleId, aclModuleName) > 0;
    }

    private String getLevel(Integer aclModuleId) {
        SysAclModule sysAclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (sysAclModule == null) {
            return null;
        }
        return sysAclModule.getLevel();
    }
}
